<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <title>数智化赋能"微情境·微宣讲"红色实践活动</title>

  <!-- 引入Swiper CSS -->
  <link rel="stylesheet" href="../templates/h5/assets/swiper-bundle.min.css">

  <!-- 引入Tailwind CSS -->
  <script src="../templates/h5/assets/tailwindcss3.4.17.css"></script>

  <!-- 引入Font Awesome -->
  <link href="../templates/h5/assets/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 引入jQuery -->
  <script src="../templates/h5/assets/jquery.min.js"></script>
  <script src="../templates/h5/assets/vconsole.min.js"></script>
  <script>
    // var vConsole = new VConsole();
    // console.log('Hello world');
  </script>

  <script>
    // 配置Tailwind自定义颜色（红色主题）
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#b71211', // 主红色
            secondary: '#FFD700', // 辅助金色
            red: {
              700: '#B91C1C',    // 稍浅红色
              800: '#991B1B',    // 深一点的红色
              900: '#7F1D1D',    // 最深红色
            }
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      /* 修复Swiper指示器样式 - 确保居中且状态稳定 */
      .swiper-pagination {
        @apply !absolute !z-50 !bottom-4 !left-1/2 !transform !-translate-x-1/2 !w-auto !flex !justify-center !items-center !gap-2;
      }
      .swiper-pagination-bullet {
        @apply !w-3 !h-3 !bg-white/50 !border !border-white/70 !transition-all !duration-300 !m-0 !rounded-full !opacity-100;
      }
      .swiper-pagination-bullet-active {
        @apply !bg-secondary !border-secondary !w-6 !rounded-full !opacity-100;
      }

      /* 导航栏样式 */
      .nav-item {
        @apply flex flex-col items-center justify-center text-gray-300 active:bg-red-800 h-full;
      }
      .nav-item.active {
        @apply text-white;
      }
      .nav-icon {
        @apply text-lg mb-1;
      }
      .nav-text {
        @apply text-xs;
      }

      /* 排序选项样式 */
      .sort-option {
        @apply py-3 text-center cursor-pointer transition-colors;
      }
      .sort-option.active {
        @apply text-secondary border-b-2 border-secondary font-medium;
      }

      /* 作品卡片样式 */
      .work-card {
        @apply bg-red-800 rounded-lg overflow-hidden border border-red-700;
      }

      /* 加载状态样式 */
      .loading-state {
        @apply text-center py-4 text-sm text-gray-300;
      }

      /* 图片占位符样式 */
      .img-placeholder {
        @apply bg-red-900 w-full h-full flex items-center justify-center;
      }
    }
  </style>

  <style>
    /* 固定轮播容器尺寸，防止动态变化导致分页器偏移 */
    #carouselContainer {
      width: 100% !important;
      height: 200px !important;
      position: relative !important;
      overflow: hidden !important;
    }

    /* 确保Swiper内部元素尺寸稳定 */
    #carouselSwiper,
    #carouselSwiper .swiper-wrapper,
    #carouselSwiper .swiper-slide {
      width: 100% !important;
      height: 100% !important;
    }

    /* 确保指示器始终可见且居中 */
    .swiper-pagination {
      display: flex !important;
      justify-content: center !important;
      align-items: center !important;
    }
  </style>
</head>
<body class="bg-primary text-white">
<div class="max-w-md mx-auto min-h-screen flex flex-col">
  <!-- 页面内容区 -->
  <div class="flex-1 overflow-y-auto">
    <!-- 轮播图容器：固定尺寸确保分页器定位稳定 -->
    <div id="carouselContainer">
      <div class="swiper" id="carouselSwiper">
        <div class="swiper-wrapper">
          <div class="swiper-slide">
            <div class="img-placeholder">
              <img src="../templates/h5/assets/pictures/banner1.jpg" class="w-full h-full object-cover" loading="lazy">
            </div>
          </div>
          <div class="swiper-slide">
            <div class="img-placeholder">
              <img src="../templates/h5/assets/pictures/banner2.jpg" class="w-full h-full object-cover" loading="lazy">
            </div>
          </div>
        </div>
      </div>
      <!-- 渐变蒙版 -->
      <div class="absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-primary to-transparent pointer-events-none z-20"></div>
      <!-- 分页器 -->
      <div class="swiper-pagination"></div>
    </div>

    <!-- 页面其他内容 -->
    <div class="p-4">
      <!-- 第一部分：活动数据统计 -->
      <div class="bg-red-800 rounded-lg p-4 mb-4 border border-red-700">
        <h2 class="text-xl font-bold mb-4 text-white">活动数据</h2>

        <!-- 数据统计卡片 -->
        <div class="grid grid-cols-3 gap-2 mb-4" id="statsCards">
          <!-- 数据将通过JS动态渲染 -->
        </div>

        <!-- 活动时间 -->
        <div id="compSetting">
          <div class="flex justify-between items-center mb-3 text-sm">
            <span>活动开始时间：</span>
            <span class="text-secondary">2025-11-22 00:00:01</span>
          </div>
          <div class="flex justify-between items-center mb-4 text-sm">
            <span>活动结束时间：</span>
            <span class="text-secondary">2025-12-14 23:59:59</span>
          </div>
        </div>

        <!-- 点赞规则 -->
        <div>
          <h3 class="font-medium mb-2 flex items-center">
            <i class="fa fa-info-circle mr-2 text-secondary"></i>点赞规则
          </h3>
          <ul class="text-xs text-gray-200 space-y-1 ml-6 list-disc">
            <li>每个微信账号每天可点赞<span id="likeCount"></span>次</li>
            <li>每次点赞间隔需超过30秒</li>
            <li>禁止恶意刷赞，违者取消资格</li>
            <li>综合得分 = 教师评分40% + 学生评分30% + 社会影响力得分30%（点赞/浏览/转发）</li>
            <li>综合得分及对应排名每周更新一次</li>
          </ul>
        </div>
      </div>

      <!-- 第二部分：作品排序和列表 -->
      <div>
        <h2 class="text-xl font-bold mb-3 text-white">参赛作品</h2>

        <!-- 排序标题栏 -->
        <div class="flex border-b border-red-700 mb-3">
          <div class="sort-option active flex-1" data-sort="index">按序号</div>
          <div class="sort-option flex-1" data-sort="likes">按点赞量</div>
          <div class="sort-option flex-1" data-sort="score">按综合得分</div>
        </div>

        <!-- 作品列表容器 -->
        <div id="workList" class="grid grid-cols-2 gap-3 pb-20">
          <!-- 作品将通过JS动态加载 -->
        </div>

        <!-- 加载状态 -->
        <div id="loadingState" class="loading-state">
          <i class="fa fa-spinner fa-spin mr-2"></i>加载中...
        </div>

        <!-- 没有更多内容提示 -->
        <div id="noMore" class="loading-state hidden">
          已经到底啦
        </div>
      </div>
    </div>
  </div>

  <!-- 底部固定导航栏 -->
  <div class="fixed bottom-0 left-0 right-0 max-w-md mx-auto bg-red-900 border-t border-red-700 z-50 h-16 flex">
    <a href="/h5/index" class="nav-item active flex-1">
      <i class="nav-icon fa fa-home"></i>
      <span class="nav-text">首页</span>
    </a>
    <a href="/h5/index_huodong" class="nav-item flex-1">
      <i class="nav-icon fa fa-calendar"></i>
      <span class="nav-text">活动</span>
    </a>
    <a href="/h5/index_paihangbang" class="nav-item flex-1">
      <i class="nav-icon fa fa-bar-chart"></i>
      <span class="nav-text">排行榜</span>
    </a>
    <a href="/h5/index_yonghu" class="nav-item flex-1">
      <i class="nav-icon fa fa-user"></i>
      <span class="nav-text">我的</span>
    </a>
  </div>
</div>

<!-- 引入Swiper JS -->
<script src="../templates/h5/assets/swiper-bundle.min.js"></script>

<script>
  // 全局接口前缀（替换为实际后端地址，需与后端接口域名一致，避免跨域）

  // 全局存储所有作品数据（用于分页）
  let allWorkData = [];
  // 分页参数
  let currentPage = 1;
  const pageSize = 6;

  $(document).ready(function() {
    // 等待轮播图图片加载完成后再初始化Swiper，避免尺寸计算错误
    const carouselImages = document.querySelectorAll('#carouselSwiper img');
    let loadedImages = 0;

    // 处理图片加载完成事件
    carouselImages.forEach(img => {
      if (img.complete) {
        loadedImages++;
        checkAllLoaded();
      } else {
        img.addEventListener('load', () => {
          loadedImages++;
          checkAllLoaded();
        });
        img.addEventListener('error', () => {
          loadedImages++;
          checkAllLoaded();
        });
      }
    });

    // 所有图片加载完成后初始化Swiper
    function checkAllLoaded() {
      if (loadedImages === carouselImages.length) {
        initSwiper();
      }
    }

    // 初始化Swiper轮播
    function initSwiper() {
      const swiper = new Swiper('#carouselSwiper', {
        loop: true,
        autoplay: {
          delay: 3000,
          disableOnInteraction: false,
        },
        pagination: {
          el: '.swiper-pagination',
          clickable: true,
          dynamicBullets: false,
          renderBullet: function (index, className) {
            return '<span class="' + className + '"></span>';
          },
        },
        touchRatio: 1,
        simulateTouch: true,
        slidesPerView: 1,
        speed: 500,
        on: {
          init: function() {
            this.update();
          }
        }
      });
    }

    // 导航栏切换效果
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
      item.addEventListener('click', function(e) {
        navItems.forEach(nav => nav.classList.remove('active'));
        this.classList.add('active');
      });
    });

    // 排序选项切换效果
    const sortOptions = document.querySelectorAll('.sort-option');
    sortOptions.forEach(option => {
      option.addEventListener('click', function() {
        sortOptions.forEach(opt => opt.classList.remove('active'));
        this.classList.add('active');
        // 排序切换时，重置分页和数据
        currentPage = 1;
        $('#workList').html('');
        $('#noMore').addClass('hidden');
        $('#loadingState').removeClass('hidden');
        // 请求对应排序的接口数据
        fetchWorkDataBySort(this.dataset.sort);
      });
    });

    /**
     * 根据排序类型请求后端接口
     * @param {string} sortType - 排序类型：index（按序号）、likes（按点赞量）、score（按综合得分）
     */
    function fetchWorkDataBySort(sortType) {
      // 显示加载状态
      $('#loadingState').removeClass('hidden');
      // 根据排序类型确定接口地址
      let apiUrl = '';
      switch(sortType) {
        case 'likes':
          apiUrl = `/h5/rank/like`; // 按点赞量接口
          break;
        case 'score':
          apiUrl = `/h5/rank/comprehensive`; // 按综合得分接口
          break;
        default: // index 按序号
          apiUrl = `/h5/rank/byid`; // 按序号接口
      }

      // AJAX请求后端接口
      $.ajax({
        url: apiUrl,
        type: "GET",
        dataType: "json",
        success: function(response) {
          // 存储所有作品数据（后端已返回排序后的列表）
          allWorkData = response;
          // 加载第一页数据
          loadWorks();
        },
        error: function(xhr, status, error) {
          console.error(`加载${sortType === 'likes' ? '点赞量排序' : sortType === 'score' ? '综合得分排序' : '序号排序'}数据失败：`, error);
          $('#loadingState').addClass('hidden');
          $('#workList').html('<div class="col-span-2 text-center py-4">数据加载失败，请稍后重试</div>');
        }
      });
    }

    /**
     * 加载当前页的作品数据（分页逻辑）
     */
    function loadWorks() {
      // 计算当前页数据范围
      const startIndex = (currentPage - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, allWorkData.length);
      const currentPageData = allWorkData.slice(startIndex, endIndex);

      // 格式化数字显示（如：1234 → 1.2k）
      const formatNumber = (num) => {
        return num >= 1000 ? (num / 1000).toFixed(1) + 'k' : num.toString();
      };

      // 渲染作品卡片
      currentPageData.forEach(work => {
        // 生成随机数用于图片占位符（避免重复）
        const randomNum = work.id || Math.floor(Math.random() * 100);
        // 作品卡片HTML（字段名需与后端CompWork实体类一致，不一致需修改）
        const workCard = `
          <div class="work-card">
            <div class="relative">
              <a href="/h5/index_zuopin?id=${work.id}"> <!-- 跳转作品详情页，携带作品ID -->
                <div class="img-placeholder">
                  <img src="${work.workCover || '作品封面'}"
                       alt="${work.title || '作品封面'}"
                       class="w-full h-32 object-cover"
                       loading="lazy">
                </div>
              </a>
                            <!-- 作品序号 -->
              <div class="absolute top-1 left-1 bg-primary text-white text-xs w-5 h-5 flex items-center justify-center rounded-full">${work.index || '--'}</div>
            </div>
            <div class="p-2">
              <!-- 作品标题（超出部分省略） -->
              <h3 class="text-sm font-medium truncate mb-1">${work.workName || '未命名作品'}</h3>
              <div class="text-xs text-gray-200 space-y-1">
                <!-- 点赞量（对应后端studentScore字段，若字段名不同需修改） -->
                <div class="flex justify-between">
                  <span><i class="fa fa-thumbs-up mr-1 text-secondary"></i>点赞</span>
                  <span>${formatNumber(work.likeCount || 0)}</span>
                </div>
                <!-- 浏览量（假设后端返回viewCount字段，无则显示0） -->
                <div class="flex justify-between">
                  <span><i class="fa fa-eye mr-1 text-secondary"></i>浏览</span>
                  <span>${formatNumber(work.lookCount || 0)}</span>
                </div>
                <!-- 综合得分（对应后端totalScore字段，若字段名不同需修改） -->
                <div class="flex justify-between">
                  <span><i class="fa fa-star mr-1 text-secondary"></i>得分</span>
                  <span>${(work.totalScore || 0).toFixed(1)}</span>
                </div>
              </div>
            </div>
          </div>
        `;
        // 添加到作品列表容器
        $('#workList').append(workCard);
      });

      // 更新分页状态
      currentPage++;
      const totalPages = Math.ceil(allWorkData.length / pageSize);
      if (currentPage > totalPages) {
        // 无更多数据
        $('#loadingState').addClass('hidden');
        $('#noMore').removeClass('hidden');
      } else {
        // 还有数据，保持加载状态
        $('#loadingState').removeClass('hidden');
        $('#noMore').addClass('hidden');
      }
    }

    // 滚动加载更多作品
    function handleScroll() {
      const scrollTop = $(document).scrollTop();
      const scrollHeight = $(document).height();
      const clientHeight = $(window).height();

      // 滚动到距离底部200px内，且有更多数据、不在加载失败状态时触发
      if (scrollTop + clientHeight >= scrollHeight - 200 &&
              currentPage <= Math.ceil(allWorkData.length / pageSize) &&
              !$('#loadingState').hasClass('hidden') &&
              $('#workList').find('.col-span-2').length === 0) {
        loadWorks();
      }
    }

    // 加载活动统计数据（保持原有逻辑）
    function loadStats() {
      $.ajax({
        url: `/h5/stats`,
        type: "GET",
        dataType: "json",
        success: function(data) {
          const formatNumber = (num) => {
            if (num >= 1000) {
              return (num / 1000).toFixed(1) + 'k';
            }
            return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
          };

          const statsHtml = `
              <div class="bg-red-900 rounded p-3 text-center">
                <div class="text-2xl font-bold text-secondary mb-1">${formatNumber(data.totalContestants || 0)}</div>
                <div class="text-xs text-gray-200">选手数量</div>
              </div>
              <div class="bg-red-900 rounded p-3 text-center">
                <div class="text-2xl font-bold text-secondary mb-1">${formatNumber(data.totalLikes || 0)}</div>
                <div class="text-xs text-gray-200">总点赞数</div>
              </div>
              <div class="bg-red-900 rounded p-3 text-center">
                <div class="text-2xl font-bold text-secondary mb-1">${formatNumber(data.totalViews || 0)}</div>
                <div class="text-xs text-gray-200">总浏览量</div>
              </div>
            `;
          $('#statsCards').html(statsHtml);

          // 渲染活动时间
          const compSettingHtml = `
        <div class="flex justify-between items-center mb-3 text-sm">
          <span>活动开始时间：</span>
          <span class="text-secondary">${data.beginTime || '未设置'}</span>
        </div>
        <div class="flex justify-between items-center mb-4 text-sm">
          <span>活动结束时间：</span>
          <span class="text-secondary">${data.endTime || '未设置'}</span>
        </div>
      `;
          $('#compSetting').html(compSettingHtml);
          const likeCountHtml = `

          <span >${data.likeCount || '未设置'}</span>

      `;
          $('#likeCount').html(likeCountHtml);

        },
        error: function(xhr, status, error) {
          console.error("活动数据加载失败：", error);
          $('#statsCards').html(`
            <div class="col-span-3 text-center py-3 text-sm text-gray-300">
              活动数据加载失败
            </div>
          `);
        }
      });
    }

    // 页面初始化：加载活动统计 + 默认按序号排序的作品数据
    loadStats();
    fetchWorkDataBySort('index');

    // 绑定滚动加载事件
    $(window).scroll(handleScroll);
  });
</script>
</body>
</html>